﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace Sustainalytics.Utils
{
    public class Cronometer
    {
        public Cronometer()
        {
            list = new List<Tuple<string, long>>();
            watch = Stopwatch.StartNew();
        }       
        public void Mark(string name)
        {
            list.Add(new Tuple<string, long>(name, watch.ElapsedMilliseconds));
            watch.Restart();
        }
        public void Restart()
        {    
            watch.Restart();
        }     
        public override string ToString()
        {
            return ToString(string.Empty);
        }
        public string ToString(string format)
        {
            var sb = new StringBuilder();
            var textFormat = "Duration[{0}] = {1} ms{2}";
            switch(format)
            {                      
                case "s": 
                      list.ForEach(r =>  sb.AppendFormat(textFormat, r.Item1 , TimeSpan.FromMilliseconds(r.Item2).TotalSeconds, System.Environment.NewLine ));
                    break;

                case "ms": 
                      list.ForEach(r =>  sb.AppendFormat(textFormat, r.Item1 , r.Item2 , System.Environment.NewLine ));
                    break;

                case "min": 
                      list.ForEach(r =>  sb.AppendFormat(textFormat, r.Item1 ,  TimeSpan.FromMilliseconds(r.Item2).TotalMinutes,  System.Environment.NewLine ));
                    break;

                default: 
                     list.ForEach(r =>  sb.AppendFormat(textFormat, r.Item1 ,  TimeSpan.FromMilliseconds(r.Item2),  System.Environment.NewLine ));
                     break;
            }
            return sb.ToString();
        }
        public void AddMarks(Cronometer cron)
        {
            list.AddRange(cron.list);
        }
        public void AddMark(string name, long durationMillisecond)
        {
            list.Add(new Tuple<string, long>(name, watch.ElapsedMilliseconds));
        }

        private Stopwatch watch;
        internal protected List<Tuple<string, long>> list;
    }
}
